axios.defaults.baseURL = 'http://localhost:8080'
Vue.prototype.$http = axios;

//1 使用axios前置拦截器，让所有的请求都携带uToken
axios.interceptors.request.use(config => {
    //携带token
    let token = localStorage.getItem("token");
    if (token) {
        config.headers['token'] = token;
    }
    return config;
}, error => {
    Promise.reject(error);
})

//2 使用axios后置拦截器，处理没有登录请求
axios.interceptors.response.use(result => {
    let data = result.data;
    if (data.success === "false" && data.message === "noLogin") {
        location.href = "login.html"
    }
    return result;
}, error => {
    Promise.reject(error);
})

//3.静态资源拦截器
let url = location.href;
if (url.indexOf('/login') !== -1 || url.indexOf('/register') !== -1) {
    localStorage.removeItem('token');
    localStorage.removeItem('logininfo');
}
let user = JSON.parse(localStorage.getItem('logininfo'));
if (!user && url.indexOf('/login') === -1 && url.indexOf('/register') === -1
    && url.indexOf('/index') === -1
    && url.indexOf('/callback') === -1
    && url.indexOf('/binder') === -1) {
    location.href = "login.html"
}

//封装公用方法 - 将字符串的参数解析为json对象
function parseUrlParams2Obj(url) {//xxx?code=xxx&state=1
    let paramStr = url.substring(url.indexOf("?") + 1);//code=xxx&state=1
    let paramArr = paramStr.split("&");//[code=xxx,state=1]
    let paramObj = {};
    for (let i = 0; i < paramArr.length; i++) {
        let paramTemp = paramArr[i];//code=xxx
        let paramName = paramTemp.split("=")[0];//code
        let paramValue = paramTemp.split("=")[1];//xxx
        paramObj[paramName] = paramValue;//{code:xxx,state:1} 动态追加对象
    }
    return paramObj;
}